﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.SqlClient;
using System.IO;


namespace InstallerBD
{
    /// <summary>
    /// Interaction logic for InstalationProces.xaml
    /// </summary>
    public partial class InstalationProces : Window, INotifyPropertyChanged
    {
        public InstalationProces(IEnumerable<SQLScript> scriptList, string server, string login, string pwd)
        {
            ScriptsCollection = scriptList;
            Login = login;
            Server = server;
            Password = pwd;
            InitializeComponent();
            Log = new ObservableCollection<string>();
            this.DataContext = this;

            this.CurrentExecScriptNumber = 0;
            onPropertyChanged("CurrentExecScriptNumber");
        }

        /// <summary>
        /// Начать выполнение скриптов
        /// </summary>
        /// <param name="scriptList">коллекция строк с путями к скриптам</param>
        public static void show(IEnumerable<SQLScript> scriptList, string server, string login, string pwd)
        {
            var dlg = new InstalationProces(scriptList, server, login, pwd);
            dlg.ShowDialog();
        }

        private void connect()
        {
            addLogRec("подключение...");
            try
            {
                Connection = new SqlConnection("Data Source=" + Server + ";Integrated Security=True");
                Connection.Open();
                addLogRec("готово.");
               // SqlTransaction Transaction = Connection.BeginTransaction();
            }
            catch (Exception ex)
            {
                addLogRec("error: " + ex.Message);
                throw;
            }


        }

        /// <summary>
        /// Выполнить скрипт
        /// </summary>
        /// <param name="filename">путь к скрипту</param>
        private void execScript(SQLScript sqlFile)
        {
            addLogRec("Выполнение скрипта: " + sqlFile.FileName);
            try
            {
                SqlCommand cmd = new SqlCommand(sqlFile.Content);//,Connection,Transaction);
                cmd.Connection = this.Connection;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.ExecuteNonQuery();
                //Transaction.Commit();
            }
            catch (Exception ex)
            {
                addLogRec("ошибка: " + ex.Message);
                return;
            }
            addLogRec("готово.");
        }


        private void disconnect()
        {         
            addLogRec("Отключение...");
            try
            {
                //Transaction.Rollback();
                this.Connection.Close();
            }
            catch (Exception ex)
            {
                addLogRec("error: " + ex.Message);
            }
            addLogRec("готово.");
        }

        private void addLogRec(string rec)
        {
            Log.Add(rec);
            onPropertyChanged("Log");
        }

        #region Свойства
        public ObservableCollection<string> Log { get; set; }

        public IEnumerable<SQLScript> ScriptsCollection { get; set; }

        public int ScriptCount
        {
            get
            {
                if (ScriptsCollection == null)
                    return 0;
                else
                    return ScriptsCollection.Count();
            }
        }

        public int CurrentExecScriptNumber { get; set; }

        public string Login { get; set; }

        public string Server { get; set; }

        public string Password { get; set; }

        private SqlConnection Connection { get; set; }

        //private SqlTransaction Transaction { get; set; }
        #endregion

        #region PropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void onPropertyChanged(string fieldName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(fieldName));
            }
        }
        #endregion

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                addLogRec("создались");
                connect();
                foreach (var sqlFile in this.ScriptsCollection)
                {
                    this.execScript(sqlFile);
                    this.CurrentExecScriptNumber++;
                    onPropertyChanged("CurrentExecScriptNumber");
                }
            }
            catch (Exception ex)
            {
                addLogRec("error: " + ex.Message);
            }
            finally
            {
                this.disconnect();
            }
        }
    }
}
